package com.synchrona.common;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import com.synchrona.update.Update;
import com.synchrona.updateSyncManager.UpdateSyncManager;
import com.synchrona.user.User;

public class SynchronizationThread extends Thread {
	private static final SynchronizationThread syncThread = new SynchronizationThread();
	private BlockingQueue<Object> syncQueue = new ArrayBlockingQueue<Object>(
			100);

	//Returns the synchronization thread
	public static SynchronizationThread getSyncThread() {
		return syncThread;
	}

	//Enqueues the object to the blocking queue
	public void syncEnqueue(Object object) {
		try {
			syncQueue.put(object);
			System.out.println("Enqueuing to the thread...");
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
			throw new RuntimeException("Unexpected interruption");
		}
	}

	//Returns the queue status 
	public synchronized boolean getStatus() {
		boolean addedStatus = false;
		try {
			Queue queue = Queue.getQueue();
			addedStatus = queue.isAddedState();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return addedStatus;
	}

	//Thread run
	public void run() {
		try {
			int count = 0;
			System.out.println("Running the synchronizations thread...");

			while (true) {
				Thread.sleep(5000L);
				Queue queue = Queue.getQueue();
				System.out.println("Got the queue...");
				boolean addedStatus = getStatus();
				System.out.println("..........Added Status: " + addedStatus
						+ " ...........");
				if (addedStatus == false) {

				} else {
					Thread.sleep(5000L);
					Object object = (Object) queue.dequeue();
					if (object != null) {
						syncEnqueue(object);
						System.out.println(".......................");
						Object obj2 = syncQueue.take();
						Update update = (Update) obj2;
						String objectName = obj2.getClass().getSimpleName();
						System.out.println("Object is: " + objectName);
						System.out.println("Processing object data... "
								+ update.getData());
						UpdateSyncManager syncManager = new UpdateSyncManager();
						syncManager.synchronizeUpdate(update);
						syncQueue.remove(obj2);
					}
				}
			}
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
			throw new RuntimeException("Unexpected interruption");
		}
	}

	//Thread shut down
	public void shutDown() throws InterruptedException {
		Thread.currentThread().stop();
	}

	//Constructor
	private SynchronizationThread() {

	}
}
